package com.yonyou.dhf.plugin;

import cn.hutool.core.convert.Convert;
import com.yonyou.iuap.ucf.common.exception.BusinessException;
import com.yonyou.ucf.mdd.ext.dao.meta.MetaDaoHelper;
import com.yonyou.ypd.bill.annotation.BillPlugin;
import com.yonyou.ypd.bill.basic.entity.IBillDO;
import com.yonyou.ypd.bill.context.YpdBillContext;
import com.yonyou.ypd.bill.plugin.AbstractBillPlugin;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.imeta.orm.schema.QueryCondition;
import org.imeta.orm.schema.QuerySchema;

import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * zyhyspring2024-be
 *
 * @author jiheng
 * @date 2024/02/24
 */
@BillPlugin(busiObj = "dhf_card", code = "dhf_card")
public class DHFCardPlugin extends AbstractBillPlugin {

    @Override
    public void beforeSave(YpdBillContext billContext) throws Exception {
        beforeSaveBusi(billContext);
        super.beforeSave(billContext);
    }

    @Override
    public void beforeDelete(YpdBillContext billContext) throws Exception {
        beforeDeleteBusi(billContext);
        super.beforeDelete(billContext);
    }

    /**
     * 保存前逻辑
     * @author jifyi
     * @param billContext
     * @throws Exception
     */
    private void beforeSaveBusi(YpdBillContext billContext) throws Exception {
        // 单据信息
        IBillDO billDO = billContext.getBillDO();
        // 单据id
        String id = Optional.ofNullable((String) billDO.getPrimaryKey()).orElse("null");
        // 项目
        String project = Convert.toStr(billDO.getAttrValue("project"));
        // 财务组织
        String finance_org = Convert.toStr(billDO.getAttrValue("finance_org"));
        QueryCondition projectCond = QueryCondition.name("project").eq(project);
        QueryCondition financeOrgCond = QueryCondition.name("finance_org").eq(finance_org);
        QueryCondition billIdCond = QueryCondition.name("id").not_eq(id);
        // 校验 经费卡 项目
        QuerySchema querySchema = QuerySchema.create()
                .addSelect("id")
                .appendQueryCondition(
                        projectCond,
                        financeOrgCond,
                        billIdCond
                );
        List<Map<String, Object>> query = MetaDaoHelper.query("zyhyspring2024.zyhyspring2024.dhf_card", querySchema);
        //存在抛出异常
        if (ObjectUtils.isNotEmpty(query)) {
            throw new IllegalArgumentException("已存在同 组织+项目 的单据！");
        }

        // 校验 经费卡 卡号
        // 卡号
        String code = Convert.toStr(billDO.getAttrValue("code"));
        QueryCondition cardNoCond = QueryCondition.name("code").eq(code);
        querySchema = QuerySchema.create().addSelect("id").appendQueryCondition(cardNoCond, billIdCond);
        query = MetaDaoHelper.query("zyhyspring2024.zyhyspring2024.dhf_card", querySchema);
        if (ObjectUtils.isNotEmpty(query)) {
            throw new IllegalArgumentException("已存在相同 经费卡号 的单据！");
        }
    }

    /**
     * 删除前逻辑
     * @author jiheng
     * @param billContext
     * @throws Exception
     */
    private void beforeDeleteBusi(YpdBillContext billContext) throws Exception {
        String id = billContext.getBillDO().getPrimaryKey();
        Map<String, Object> ecInfo = MetaDaoHelper.queryOne(
                "zyhyspring2024.zyhyspring2024.dhf_card",
                QuerySchema.create()
                        .addSelect("*")
                        .appendQueryCondition(
                                QueryCondition.name("id").eq(id)
                        )
        );

        if (ObjectUtils.isEmpty(ecInfo)) {
            throw new BusinessException("删除规则执行失败，经费卡未找到");
        }

        String project = Convert.toStr(ecInfo.get("project"));
        if (StringUtils.isBlank(project)) {
            throw new BusinessException("未获取到项目");
        }
        List<Map<String, Object>> applyOrderInfoList = MetaDaoHelper.query(
                "zyhyspring2024.zyhyspring2024.dhf_apply_orders",
                QuerySchema.create()
                        .addSelect("*")
                        .appendQueryCondition(
                                QueryCondition.name("project").eq(project)
                        )
        );
        if (ObjectUtils.isNotEmpty(applyOrderInfoList)) {
            throw new BusinessException("经费卡已被请购单引用，不可删除");
        }
    }

}
